package com.googlecode.horncomb.bean.order;

import java.io.Serializable;
import java.util.List;

import org.apache.commons.collections.map.ListOrderedMap;
import org.springframework.util.Assert;

/**
 * 排序定义
 * @author Daniel
 * @version $LastChangedRevision$
 */
public class DefaultOrder implements Order, Serializable {
	private static final long serialVersionUID = -8060540944644138604L;

	public DefaultOrder() {
		super();
	}

	public DefaultOrder(OrderToken... sorts) {
		super();
		for (OrderToken s : sorts) {
			this.addSortToken(s);
		}
	}

	protected ListOrderedMap tokens = new ListOrderedMap();

	public DefaultOrder addSortToken(String property) {
		return this.addSortToken(property, true);
	}

	public DefaultOrder addSortToken(String property, boolean ascending) {
		return (DefaultOrder)this.addSortToken(new DefaultOrderToken(property, ascending));
	}

	/**
	 * @see com.googlecode.horncomb.bean.order.Order#addSortToken(com.googlecode.horncomb.bean.order.OrderToken)
	 */
	public Order addSortToken(OrderToken sort) {
		Assert.notNull(sort);
		Assert.hasText(sort.getProperty());
		String property = sort.getProperty();
		if (tokens.containsKey(property)) {
			tokens.remove(property);
		}
		this.tokens.put(property, sort);
		return this;
	}

	/**
	 * @see com.googlecode.horncomb.bean.order.Order#getTokens()
	 */
	@SuppressWarnings("unchecked")
	public List<OrderToken> getTokens() {
		return tokens.valueList();
	}
}
